package com.iot.manager.network;

import android.content.Context;
import android.util.Log;
import com.iot.manager.BuildConfig;
import com.iot.manager.network.interceptors.AuthInterceptor;
import com.iot.manager.network.interceptors.ErrorInterceptor;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import java.util.concurrent.TimeUnit;

public class RetrofitClient {
    private static final String TAG = "RetrofitClient";
    private static final String BASE_URL = "http://123.56.226.74:3001/api/";
    private static RetrofitClient instance;
    private final Retrofit retrofit;
    private final AuthInterceptor authInterceptor;

    private RetrofitClient() {
        authInterceptor = new AuthInterceptor();
        ErrorInterceptor errorInterceptor = new ErrorInterceptor();

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(authInterceptor)
                .addInterceptor(errorInterceptor)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static synchronized RetrofitClient getInstance() {
        if (instance == null) {
            instance = new RetrofitClient();
        }
        return instance;
    }

    public static synchronized void init(Context context) {
        if (instance == null) {
            instance = new RetrofitClient();
        }
    }

    public ApiService getApiService() {
        return retrofit.create(ApiService.class);
    }

    public void setToken(String token) {
        authInterceptor.setToken(token);
    }

    public String getBaseUrl() {
        return BASE_URL;
    }
} 